<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ include file="/WEB-INF/view/jsp/public/include.base.jsp" %>
<style type="text/css">
    /* css style: */
    html, body {
        -moz-user-select: none;
        -khtml-user-select: none;
        user-select: none;
    }

    .role-tags {
        float: left;
        width: 20%;
    }

    .role-tags ul {
        list-style: none;
        display: inline-block;
    }

    .tag {
        width: 200px;
        height: 60px;
        margin: 10px auto;
        background-color: #E4E4E4;
        position: relative;
        text-align: center;
    }

    .tag:hover {
        background-color: #666666;
    }

    .tag p {
        padding: 20px 0;
    }

    .tag p:hover {
        color: #fff;
    }

    .arrow {
        position: absolute;
        top: 14px;
        right: -32px; /* 圆角的位置需要细心调试哦 */
        width: 0;
        height: 0;
        font-size: 0;
        border: solid 16px;
        border-color: #fff #fff #fff #666666;
    }

    .active div {
        background-color: #666666;
    }

    .active p {
        color: #fff;
    }

    .content-main {
        float: right;
        width: 75%;
        background-color: #F2F2F2;
        min-height: 400px;
        position: relative;
    }

    .content-main-body {
        padding: 10px;
        margin-bottom: 50px;
    }

    .content-main-footer {
        width: 100%;
        position: absolute;
        bottom: 0;
        padding: 10px;
        text-align: center;
    }
</style>


<div class="panel">
    <!-- Javascript -->

    <div class="panel-body">
        <div class="role-tags" style="text-align: center;">
            <ul>
                <c:forEach items="${roles}" var="role" varStatus="status">
                    <li class="<c:if test="${status.index == 0}">active</c:if>" onclick="active(${role.id})">
                        <div id="${role.id}" class="tag">
                            <p href="javascript:void(0);"><span>${role.name}</span></p>
                            <c:if test="${status.index == 0}">
                                <div class="arrow"></div>
                            </c:if>
                        </div>
                    </li>
                </c:forEach>
                <li class="create" onclick="create()">
                    <div class="tag">
                        <p href="javascript:void(0);"><i class="fa fa-plus"></i><span>新增权限</span></p>
                    </div>
                </li>
            </ul>

        </div>
        <div class="content-main">
            <div class="content-main-body">
                <form class="form-horizontal" id="roleMenuForm">
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">权限名称：</label>

                        <div class="col-sm-5">
                            <input type="text" class="form-control" id="name" name="name"
                                   <c:if test="${not empty roles}">value="${roles[0].name}"</c:if>
                                   placeholder="请输入权限名称">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">权限编码：</label>

                        <div class="col-sm-5">
                            <input type="text" class="form-control" id="code" name="code"
                                   <c:if test="${not empty roles}">value="${roles[0].code}"</c:if>
                                   placeholder="请输入权限编码">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">权限：</label>

                        <div class="col-sm-5">
                            <div id="tree" style="height: 400px;overflow-y: auto;"></div>
                        </div>
                        <c:if test="${not empty roles}">
                            <script type="text/javascript">
                                init.push(function () {
                                    var menuIds = "${roles[0].menuIds2Json}";
                                    var unchecked = $('#tree').treeview('getUnchecked');
                                    $.each(JSON.parse(menuIds), function (index, item) {
                                        $.each(unchecked, function (i, node) {
                                            if (node.id == item) {
                                                $('#tree').treeview('checkNode', [node.nodeId, {silent: true}]);
                                                return false;
                                            }
                                        });
                                    });
                                });
                            </script>
                        </c:if>
                    </div>
                    <input type="hidden" id="id" name="id"
                           <c:if test="${not empty roles}">value="${roles[0].id}"</c:if> />
                    <input type="hidden" id="menuIds2Json" name="menuIds2Json"
                           <c:if test="${not empty roles}">value="${roles[0].menuIds2Json}"</c:if> />
                </form>
            </div>
            <div class="content-main-footer">
                <button type="button" style="margin:5px;" class="btn btn-primary btn-lg" onclick="save()">
                    <span>保存</span>
                </button>
                <button type="button" style="margin:5px;" class="btn btn-default btn-lg" onclick="cancel()">
                    <span>取消</span>
                </button>
                <button type="button" style="margin:5px 5px 5px 50px;" class="btn btn-danger btn-lg"
                        onclick="removeRole()">
                    <span>删除</span>
                </button>
            </div>

        </div>
    </div>
</div>

<script type="text/javascript">
    var createTree = function () {
        $('#tree').treeview({
            data: getTree(),
            levels: 5,
            showCheckbox: true,
            highlightSelected: false
        });
        $('#tree').on('nodeChecked', function (event, data) {
            if (null != data.nodes) {
                $.each(data.nodes, function (index, node) {
                    $('#tree').treeview('checkNode', [node.nodeId, {silent: true}]);
                });
            } else {
                $('#tree').treeview('checkNode', [data.parentId, {silent: true}]);
            }
        });
        $('#tree').on('nodeUnchecked', function (event, data) {
            if (null != data.nodes) {
                $.each(data.nodes, function (index, node) {
                    $('#tree').treeview('uncheckNode', [node.nodeId, {silent: true}]);
                });
            }
        });
    };
    var getTree = function () {
        var treeData = null;
        $.ajax({
            type: 'GET',
            async: false,
            url: '${pageContext.request.contextPath}/system/menu/tree.json',
            success: function (data) {
                if (data.meta.success) {
                    treeData = data.data;
                }
            },
            error: function () {
            }
        });
        return treeData;
    };

    var active = function (id) {
        var $div = $('#' + id);
        if (!$div.parent().hasClass("active")) {
            $('.active').removeClass('active');
            $('.arrow').remove();
            $div.parent().addClass("active");
            $div.append('<div class="arrow"></div>');
            loadRole(id);
        }
    };

    var loadRole = function (id) {
        $("#id").val("");
        $("#name").val("");
        $("#code").val("");
        createTree();
        if (id === "new")
            return;
        $.ajax({
            url: '${pageContext.request.contextPath}/system/role/' + id,
            type: 'GET',
            success: function (data) {
                if (data.meta.success) {
                    $("#id").val(data.data.id);
                    $("#name").val(data.data.name);
                    $("#code").val(data.data.code);
                    var menuIds = data.data.menuIds;
                    var unchecked = $('#tree').treeview('getUnchecked');
                    $.each(menuIds, function (index, item) {
                        $.each(unchecked, function (i, node) {
                            if (node.id == item) {
                                $('#tree').treeview('checkNode', [node.nodeId, {silent: true}]);
                                return false;
                            }
                        });
                    });
                }
            },
            error: function () {
            }
        });
    };

    var create = function () {
        if ($(".role-tags ul li").hasClass("new")) {
            return;
        }
        $("#id").val("");
        $("#name").val("");
        $("#code").val("");
        createTree();
        $('.active').removeClass('active');
        $('.arrow').remove();
        var strHtml = '';
        strHtml += '<li class="new active" onclick="active(\'new\')">';
        strHtml += '<div id="new" class="tag">';
        strHtml += '<p href="javascript:void(0);"><span>NEW</span></p>';
        strHtml += '<div class="arrow"></div>';
        strHtml += '</div>';
        strHtml += '</li>';
        $(".create").before(strHtml);
    };

    var save = function () {
        if (!$("#roleMenuForm").valid()) {
            return;
        }
        //获取树形菜单选中项
        var checkedArr = new Array();
        $.each($('#tree').treeview('getChecked'), function (index, item) {
            checkedArr.push(item.id);
        });

        var params = {};
        params.id = $('#id').val();
        params.name = $('#name').val();
        params.code = $('#code').val();
        params.menuIds2Json = JSON.stringify(checkedArr);
        $.ajax({
            url: '${pageContext.request.contextPath}/system/role/saveOrUpdate',
            type: 'POST',
            data: params,
            success: function (data) {
                if (data.meta.success) {
                    bootbox.alert({
                        title: '<span style="font-size: 14px;"><B>提示</B></span>',
                        message: "<div style='text-align: left;'><span style='font-size: 14px;'>操作成功</span></div>",
                        callback: function () {
                            document.location.reload();
                        },
                        className: "bootbox-sm"
                    });
                }
            },
            error: function () {
            }
        });
    };

    var cancel = function () {
        document.location.reload();
    };

    var removeRole = function () {
        bootbox.confirm({
            title: '<span style="font-size: 14px;"><B>提示</B></span>',
            message: "<div style='text-align: left;'><span style='font-size: 14px;'>确认要删除吗?</span></div>",
            callback: function (result) {
                if (result) {
                    var id = $("#id").val();
                    $.ajax({
                        type: 'POST',
                        url: '${pageContext.request.contextPath}/system/role/remove',
                        data: {id: id},
                        success: function (data) {
                            if (data.meta.success) {
                                bootbox.alert({
                                    title: '<span style="font-size: 14px;"><B>提示</B></span>',
                                    message: "<div style='text-align: left;'><span style='font-size: 14px;'>操作成功</span></div>",
                                    callback: function () {
                                        document.location.reload();
                                    },
                                    className: "bootbox-sm"
                                });
                            }
                        },
                        error: function () {
                        }
                    });
                }
            },
            buttons: {
                confirm: {label: '确定'},
                cancel: {label: '取消'}
            },
            className: "bootbox-sm"

        });
    };
    $(document).ready(function () {
        var id = "${roles[0].id}";
        loadRole(id);
        //createTree();
        $("#roleMenuForm").validate({
            ignore: '.ignore',
            focusInvalid: false,
            rules: {
                'name': {
                    required: true,
                    remote: {
                        url: contextPath + "/system/role/check",
                        type: "post",
                        dataType: "json",
                        data: {
                            key: 'name',
                            value: function () {
                                return $.trim($('#name').val());
                            }
                        }
                    }
                },
                'code': {
                    required: true,
                    remote: {
                        url: contextPath + "/system/role/check",
                        type: "post",
                        dataType: "json",
                        data: {
                            key: 'code',
                            value: function () {
                                return $.trim($('#code').val());
                            }
                        }
                    }
                }
            },
            messages: {
                'name': {
                    required: '权限名称不能为空',
                    remote: '权限名称已存在'
                },
                'code': {
                    required: '权限编码不能为空',
                    remote: '权限编码已存在'
                }
            }
        });
    });
</script>
